import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:oktoast/oktoast.dart';
import 'package:rapid_kit/rapid_kit.dart';

import '../../pages/Home/home_page.dart';
import '../../repository/api.dart';
import '../../theme.dart';
import '../../utils/LogUtils.dart';
import '../../utils/snack_tips.dart';
import '../../widgets/lifecycle_aware.dart';
import 'live/live_attempt.dart';
import 'live/live_bottom.dart';
import 'live/live_middle.dart';
import 'live/live_player.dart';
import 'live/live_quality.dart';
import 'live/live_top.dart';
import 'live/ptz_pannel.dart';
import 'local_replay/local_replay_player.dart';

/// 播放器页面
class LivePage extends StatefulWidget {
  final String deviceId;
  final String deviceName;
  final int cameraCount;
  final bool lan;

  const LivePage(
      {super.key,
      required this.deviceId,
      required this.deviceName,
      required this.cameraCount,
      required this.lan});

  @override
  State<LivePage> createState() => LivePageState();
}

class LivePageState extends LifecycleAwareState<LivePage> with WidgetsBindingObserver {
  // 创建一个 GlobalKey
  static final GlobalKey<LivePageState> globalliveKey =
  GlobalKey<LivePageState>();


  final String _tag = '_live_page';
  final String _featurePtz = "SupportPTZ";

  late String _deviceId;
  late String _deviceName;
  late int _cameraCount;
  late bool _lan;

  late Pipe _pipe;

  late MediaChat _mediaChat;

  Map<String, dynamic>? _features;

  int _selectedQualityIndex = -1;

  bool _liveMode = true;
  late LivePlayer _livePlayer;
  late LocalReplayPlayer _localReplayPlayer;

  LocalReplaySpeed _speed = LocalReplaySpeed.x1;

  bool _chatStarted = false;
  bool _audioMuted = false;
  bool _videoCapturing = false;
  bool _rendering = false;
  bool _establishFailed = false;
  bool _ptzSupported = false;
  bool _ptzPanelVisible = false;
  bool _localStorageExist = false;

  bool _acquireTextureClear = false;

  int _onVolumeinitTapdata = 0;

  @override
  Widget build(BuildContext context) {
    final title = _deviceName.isEmpty ? _deviceId : _deviceName;
    return scaffold(title, context, _root());
  }

  // 播放内容主体
  Widget _root() {
    return WillPopScope(
      onWillPop: () async {
        // if (_pipe != null) {
        //   _pipe.abolish();
        //   _pipe.destroy();
        // }

        // 在这里定义返回按键触发的事件
        print('返回按键被触发');
        HomePageState.globalKeytwo.currentState?.reloadData();
        // 返回true允许返回，返回false阻止返回
        return true;
      },
      child: LayoutBuilder(
        builder: (context, constraints) {
          double width = constraints.maxWidth;
          double height = width * 9 / 16;

          return Column(
            children: <Widget>[
              _top(width, height),
              if (!_lan) _middle(),
              if (!_lan) _bottom(),
            ],
          );
        },
      ),
    );
  }

  // 播放器组件
  Widget _middle() {
    return MiddleSectionWidget(
      isLiveMode: _liveMode,
      isSpeedUp: _speed != LocalReplaySpeed.x1,
      isChatStarted: _chatStarted,
      isAudioMuted: _audioMuted,
      isVideoCapturing: _videoCapturing,
      selectedQualityIndex: _selectedQualityIndex,
      isPtzSupported: _ptzSupported,
      isPtzPanelVisible: _ptzPanelVisible,
      onChatTap: _onChatTap,
      onVolumeTap: _onVolumeTap,
      onQualityTap: _onQualityTap,
      onCapture: _onCapture,
      onRecordTap: _onRecordTap,
      onPtzTap: _onPtzTap,
      onPlaybackSpeedTap: _onPlaybackSpeedTap,
    );
  }

  // 多目摄像头设置
  void _onPlaybackSpeedTap() {
    if (_liveMode) return;
    _speed = _speed == LocalReplaySpeed.x1
        ? LocalReplaySpeed.x4
        : LocalReplaySpeed.x1;
    _localReplayPlayer.speed(_speed);
    setState(() => _speed = _speed);
  }

  void _onPtzTap() {
    if (_ptzPanelVisible) {
      setState(() {
        _ptzPanelVisible = false;
      });
    } else {
      setState(() {
        _ptzPanelVisible = true;
      });
    }
  }

  // 操作声音
  void _onVolumeTap() {
    if (_onVolumeinitTapdata == 1) {
      print("=======操作声音=========");
      if (_liveMode) {
        _livePlayer.mute();
        _audioMuted = _livePlayer.audioMuted;
      } else {
        _localReplayPlayer.mute();
        _audioMuted = _localReplayPlayer.audioMuted;
      }
    } else {
      showEqputvoiceDialog(
        context: context,
        dismissClick: () {
          // 这里是用户点击“我知道了”按钮后的回调逻辑
          // showToast("提示成功");
        },
      );
    }

    setState(() => _audioMuted = _audioMuted);
  }

  void _onVolumeinitTap() {
    if (_liveMode) {
      _livePlayer.mute();
      _audioMuted = _livePlayer.audioMuted;
    } else {
      _localReplayPlayer.mute();
      _audioMuted = _localReplayPlayer.audioMuted;
    }
  }

  Future<void> showEqputvoiceDialog({
    required BuildContext context,
    GestureTapCallback? dismissClick,
  }) async {
    await showDialog(
      context: context,
      barrierDismissible: false, // 点击外部不关闭对话框
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("打开设备声音？"),
          content: const Text("请在设置打开录音保护，收取声音"), // 如果需要内容可以在这里添加
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                dismissClick?.call();
              },
              child: const Text(
                "我知道了",
                style: TextStyle(color: Colors.red), // 设置文本颜色为红色
              ),
            ),
          ],
        );
      },
    );
  }

  void _onQualityTap() async {
    if (!_liveMode) return;
    if (!_pipe.isEstablished) return;
    final resp = await InstructStandard.quality(_pipe);
    if (!mounted) return;
    if (resp.success) {
      LogUtils.w(resp.data);
      _onPickQualities(resp.data!);
    } else {
      SnackTips.show(context, "unable to get qualities.");
    }
  }

  void _onPickQualities(List<Quality> qualities) {
    if (!_liveMode) return;
    QualityPicker(
      context: context,
      selectedQualityIndex: _selectedQualityIndex,
      onQualitySelected: (index) {
        if (_selectedQualityIndex != index) {
          setState(() {
            _selectedQualityIndex = index;
          });
          _livePlayer.switchQuality(qualities[index].value);
        }
      },
    ).show(qualities);
  }

  void _onCapture() async {
    int value = -1;
    if (_liveMode) {
      value = await _livePlayer.capture();
    } else {
      value = await _localReplayPlayer.capture();
    }

    if (value == 0) {
      SnackTips.show(context, "截图保存成功.");
    } else if (value == -1) {
      SnackTips.show(context, "截图保存失败.");
    } else if (value == -2) {
      SnackTips.show(context, "请授权访问相册.");
    } else if (value == -3) {
      SnackTips.show(context, "请到系统设置中，手动授权访问相册.");
    }
  }

  void _onRecordTap() async {
    int value = -1;
    if (_liveMode) {
      value = await _livePlayer.record();
    } else {
      value = await _localReplayPlayer.record();
    }

    if (value == 0) {
      SnackTips.show(context, "开始录像...");
    } else if (value == 1) {
      SnackTips.show(context, "录像保存成功.");
    } else if (value == -1) {
      SnackTips.show(context, "录像保存失败.");
    } else if (value == -2) {
      SnackTips.show(context, "请授权访问相册.");
    } else if (value == -3) {
      SnackTips.show(context, "请到系统设置中，手动授权访问相册.");
    }

    setState(() {
      _videoCapturing = _livePlayer.videoCapturing;
    });
  }

  void _onChatTap() async {
    if (!_pipe.isEstablished) return;
    if (!_liveMode) {
      SnackTips.show(context, "回放模式下无法开启对讲.");
      return;
    }

    bool microphoneGranted =
        await RuntimePermissions.accessGranted(PermissionType.microphone);
    if (!microphoneGranted) {
      final state =
          await RuntimePermissions.requestAccess(PermissionType.microphone);
      if (state == PermissionState.denied) {
        SnackTips.show(context, "请到系统设置中，手动授权麦克风权限.");
        return;
      }
      return;
    }

    if (_mediaChat.started()) {
      _mediaChat.stop();
    } else {
      _mediaChat.start();
    }

    // Disable audio while chatting.
    if (!_livePlayer.audioMuted) {
      _livePlayer.mute();
    }

    setState(() {
      _audioMuted = _mediaChat.started();
    });

    setState(() {
      _chatStarted = _mediaChat.started();
    });
  }

  Widget _top(double width, double height) {
    return Container(
      width: width,
      height: height,
      color: SampleThemeConfigure.colorVideoBackground,
      child: _playerFrame(),
    );
  }

  Widget _bottom() {
    return Expanded(
      child: Stack(
        children: [
          LiveBottomEntryWidget(
            deviceId: _deviceId,
            deviceName: _deviceName,
          ),
          PtzPanelWidget(
              deviceId: _deviceId,
              panelVisible: _ptzSupported && _ptzPanelVisible),
        ],
      ),
    );
  }

  Widget _smallPlayerContainer(Widget child, {bool isLeft = true}) {
    return Positioned(
      bottom: 0,
      left: isLeft ? 0 : null,
      right: isLeft ? null : 0,
      child: _subPlayerTextureSizedBox(context, child),
    );
  }

  SizedBox _subPlayerTextureSizedBox(BuildContext context, Widget child) {
    var width = MediaQuery.of(context).size.width / 3;
    return SizedBox(
      width: width,
      height: (width) * 9 / 16,
      child: Container(
        decoration: BoxDecoration(
          boxShadow: [
            BoxShadow(
              color: Colors.black54.withOpacity(0.3),
              spreadRadius: 2,
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: child,
      ),
    );
  }

  Widget _playerFrame() {
    if (_acquireTextureClear) {
      return Container();
    }

    return Stack(
      children: [
        _playerBackground(),
        (_liveMode
            ? _livePlayer.textureOfCamera0()
            : _localReplayPlayer.textureOfCamera0()),
        if (_liveMode
            ? _livePlayer.existCamera1()
            : _localReplayPlayer.existCamera1())
          _smallPlayerContainer(
              _liveMode
                  ? _livePlayer.textureOfCamera1()
                  : _localReplayPlayer.textureOfCamera1(),
              isLeft: true),
        if (_liveMode
            ? _livePlayer.existCamera2()
            : _localReplayPlayer.existCamera2())
          _smallPlayerContainer(
              _liveMode
                  ? _livePlayer.textureOfCamera2()
                  : _localReplayPlayer.textureOfCamera2(),
              isLeft: false),
        if (!_rendering && !_establishFailed) bufferingWidget(),
        if (_establishFailed) _establishFailedWidget(),
        if (_localStorageExist) _localStorageCard(),
      ],
    );
  }

  Positioned _playerBackground() {
    return Positioned.fill(
      child: Container(color: SampleThemeConfigure.colorVideoBackground),
    );
  }

  Widget _localStorageCard() {
    return Positioned(
      right: 10,
      top: 10,
      child: InkWell(
        onTap: _switchLiveAndPlayback,
        child: Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(
            color: Colors.white,
            shape: BoxShape.circle,
          ),
          child: Icon(
            Icons.sd_card,
            color: !_liveMode
                ? SampleThemeConfigure.colorActive
                : SampleThemeConfigure.colorTextHint,
            size: 30,
          ),
        ),
      ),
    );
  }

  void _switchLiveAndPlayback() {
    if (!_localStorageExist) {
      SnackTips.show(context, "设备没有存储卡！");
      return;
    }

    if (_liveMode) {
      _livePlayer.pause();
      _localReplayPlayer.resume();
    } else {
      _localReplayPlayer.pause();
      _livePlayer.resume();
    }

    setState(() {
      _acquireTextureClear = true;
    });

    Future.delayed(Duration(milliseconds: 100), () {
      setState(() {
        _acquireTextureClear = false;
        _liveMode = !_liveMode;
      });
    });
  }

  Widget _establishFailedWidget() {
    return EstablishFailedWidget(
      onRetry: () {
        _pipe.establish();
        setState(() => _establishFailed = false);
      },
    );
  }

  @override
  void initState() {
    super.initState();

    //2.页面初始化的时候，添加一个状态的监听者
    WidgetsBinding.instance?.addObserver(this);

    showToast("===================执行播放==============");

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff),
      statusBarIconBrightness: Brightness.dark,
    ));

    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 在页面渲染完毕之后执行延迟操作
      Future.delayed(const Duration(seconds: 3), () async {
        LogUtils.w("=========获取封面=========");

        bool swtich = await Api.instance.eqcoverimg(deviceid: _deviceId);
        if (swtich) {
          showToast("设备传输正常");
        }
      });
    });

    WidgetsBinding.instance.addObserver(this);

    _deviceId = widget.deviceId;
    _deviceName = widget.deviceName;
    _cameraCount = widget.cameraCount;
    _lan = widget.lan;

    _preparePipe();
    _preparePlayer();
    _prepareMediaChat();

    // after all prepared, start to establish pipe
    _pipe.establish();

    if (_liveMode) {
      _livePlayer.resume();
    } else {
      _localReplayPlayer.resume();
    }
  }



  @override
  void resume() {}

  @override
  void pause() {
    _livePlayer.pause();
    _localReplayPlayer.pause();
    _mediaChat.stop();
  }

  @override
  void dispose() {
    super.dispose();

    //3. 页面销毁时，移出监听者
    WidgetsBinding.instance?.removeObserver(this);

    LogUtils.w("执行销毁播放页面");

    _livePlayer.dispose();
    _localReplayPlayer.dispose();

    _pipe.abolish();
    _pipe.destroy();
    _mediaChat.destroy();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
    //进入应用时候不会触发该状态 应用程序处于可见状态，并且可以响应用户的输入事件。它相当于 Android 中Activity的onResume
      case AppLifecycleState.resumed:
        print("===进入前台===");
        break;
    //应用状态处于闲置状态，并且没有用户的输入事件，
    // 注意：这个状态切换到 前后台 会触发，所以流程应该是先冻结窗口，然后停止UI
      case AppLifecycleState.inactive:
        print("应用处于闲置状态，这种状态的应用应该假设他们可能在任何时候暂停 切换到后台会触发======");
        break;
    //当前页面即将退出
      case AppLifecycleState.detached:
        print("当前页面即将退出======");
        break;
    // 应用程序处于不可见状态
      case AppLifecycleState.paused:
        print("应用处于不可见状态 后台======");
        break;
      case AppLifecycleState.hidden:
        // TODO: Handle this case.
    }
  }

  void reloadData () {

    LogUtils.w("===================重新播放==============");

    // WidgetsBinding.instance.addObserver(this);
    //
    // _deviceId = widget.deviceId;
    // _deviceName = widget.deviceName;
    // _cameraCount = widget.cameraCount;
    // _lan = widget.lan;
    //
    // _preparePipe();
    // _preparePlayer();
    // _prepareMediaChat();
    //
    // // after all prepared, start to establish pipe
    // _pipe.establish();
    //
    // if (_liveMode) {
    //   _livePlayer.resume();
    // } else {
    //   _localReplayPlayer.resume();
    // }
  }

  void _preparePipe() {
    _pipe = Pipe.create(_deviceId);
    if (_lan) _pipe.lan();
    _pipe.listen((state) {
      if (state == PipeState.established) {
        if (_features == null) {
          _queryAbilities();
          _querySdCardState();
          // 获取声音状态
          _onQuality();
        }
      } else if (state == PipeState.failed) {
        setState(() {
          _establishFailed = true;
        });
      } else {
        setState(() {
          _establishFailed = false;
          _rendering = false;
        });
      }
    });
  }

  void _onQuality() async {
    LogUtils.w("========执行1=======");
    if (!_pipe.isEstablished) return;
    LogUtils.w("========执行2=======");
    final resp = await InstructStandard.microphoneSwitch(_pipe);
    if (!mounted) return;
    if (resp.success) {
      LogUtils.w("声音开关${resp.data}");
      _onVolumeinitTapdata = resp.data ?? 0;
      if (resp.data == 1) {
      } else {
        _onVolumeinitTap();
      }
    } else {
      showToast("获取声音失败");
    }
  }

  void _querySdCardState() async {
    final resp = await InstructStandard.storageState(_pipe);
    if (!mounted) return;
    if (!resp.success) return;
    final total = resp.data?.total ?? 0;
    setState(() => _localStorageExist = total > 0);
  }

  void _queryAbilities() async {
    final resp = await InstructStandard.ability(_pipe);
    if (!mounted) return;
    if (!resp.success) return;
    _features = resp.data?.features;
    setState(() {
      _ptzSupported = _isPtzSupported();
    });
  }

  bool _isPtzSupported() {
    if (_features == null) return false;
    if (!(_features?.containsKey(_featurePtz) ?? false)) return false;

    // Notice: The value of "SupportPTZ" may be a list of string or a string.
    if (_features![_featurePtz] is List<dynamic>) {
      final ptzList = _features![_featurePtz] as List<dynamic>;
      // any item in the list is not "no", then PTZ is supported.
      return ptzList.any((element) => element.toLowerCase() != "no");
    } else {
      final ptzConfig = _features![_featurePtz] as String;
      return ptzConfig.isNotEmpty && ptzConfig.toLowerCase() != "no";
    }
  }

  void _preparePlayer() {
    renderStateListener(state) {
      setState(() {
        _rendering = state != RenderState.buffering;
      });
    }

    _livePlayer = LivePlayer(_pipe);
    _livePlayer.prepare(_cameraCount);
    _livePlayer.renderStateListener = renderStateListener;

    _localReplayPlayer = LocalReplayPlayer(_pipe);
    _localReplayPlayer.prepare(_cameraCount);
    _localReplayPlayer.renderStateListener = renderStateListener;
  }

  void _prepareMediaChat() {
    _mediaChat = MediaChat.create(_pipe);
    _mediaChat.prepare();
  }
}
